package com.shujia;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

public class Demo3Trans {
    public static void main(String[] args) throws Exception {
        //1、创建生产者
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092");

        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        properties.setProperty("transactional.id", "asdasdasd");

        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        //初始化事务
        producer.initTransactions();

        //开启事务
        producer.beginTransaction();

        //2、生产数据
        producer.send(new ProducerRecord<>("words", "flink"));

        System.out.println("等待5秒");
        Thread.sleep(5000);

        producer.send(new ProducerRecord<>("words", "spark"));

        //提交事务
        producer.commitTransaction();

        producer.flush();

        //关闭生产者
        producer.close();
    }
}
